package com.gather.system;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.api.service.GatherService;
import com.common.dto.SnatchItem;
import com.common.dto.WebConfig;
import com.common.dto.WebNode;
import com.common.system.SystemData;
import com.common.utils.PropsLoader;
import com.common.utils.XmlConfigUtil;
import com.gather.constant.SystemConstant;
import com.gather.core.HeartThread;
import com.gather.service.AccountService;
import com.gather.service.WorkService;


/**
 * @author ltj 节点管理系统初始化类
 */
@Component
public class SystemMgr {
	private static Logger logger = Logger.getLogger(SystemMgr.class.getName());
	@Autowired
	private PropsLoader propsLoader;
	
	@Autowired
	AccountService accountManageService;
	
	@Autowired
	WorkService taskService;
	
	@Autowired
	GatherService gatherService;
	
	@Autowired
	HeartThread heartThread;
	
	public static final boolean TEST = true;
	
	/**
	 * 初始化的数据
	 */
	@PostConstruct
	public void init() {
		initCfgs();
		if(!TEST){
			initAccount();
			initSnatch();
		}
	}

	/**
	 * 销毁系统级别的资源
	 */
	@PreDestroy
	public void destroy() {
	}

	/**
	 * 初始化的守护线程
	 */
	private void initDaemon() {
		heartThread.start();
		logger.info("心跳启动成功!");

	}

	
	/**
	 * 初始化的系统配置
	 */
	private void initCfgs() {
		FileInputStream fileInputStream = null;
		try {
			ClassLoader loader = SystemMgr.class.getClassLoader();
			URL url = loader.getResource(SystemConstant.SNATCH_CONFIG);
			fileInputStream = new FileInputStream(new File(url.getFile()));
			WebConfig webConfig = XmlConfigUtil.xmlChangeNodeWeb(fileInputStream);
			SystemData.webConfig = webConfig;
									
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fileInputStream!=null){
				try {
					fileInputStream.close();
					fileInputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void initAccount(){
		for(WebNode webNode : SystemData.webConfig.getWebNodes()){
			if(webNode.isLoginAuto()){
				accountManageService.loginAccount(webNode.getWebCode());
			}
		}
	}
	
	public void initSnatch(){
		for(WebNode webNode : SystemData.webConfig.getWebNodes()){
				for(SnatchItem snatchItem : webNode.getSnatchItems()){
					if(snatchItem.isAuto()){
						gatherService.snatchTask(webNode.getWebCode(),snatchItem.getItemOnlyCode(), 1);
					}
					
			}
		}
	}
}
